const app = getApp()
var websocket = require('../../utils/websocket.js');
var utils = require('../../utils/util.js');
const {
  $Toast
} = require('../../dist/base/index');
var interval;

Page({
  data: {
    newslist: [],
    userInfo: {},
    scrollTop: 0,
    increase: false, //图片添加区域隐藏
    aniStyle: true, //动画效果
    message: "",
    previewImgList: []
  },

  onLoad: function() {
    var that = this;

    var chatInfo = wx.getStorageSync("chatInfo");

    if (!chatInfo) {
      $Toast({
        content: '请先登录!',
        type: 'error'
      });
      wx.reLaunch({
        url: '/pages/userinfo/userinfo',
      });
    } else {
      this.setData({
        chatInfo: chatInfo
      });

			websocket.connect(this.data.chatInfo, function(res) {
				if(JSON.parse(res.data).data.length == 0) {
					that.setData({
						newslist: []
					});
				} else {
					var data = JSON.parse(res.data).data;
					data[0].flagtime = true;

					for (var i = 1; i < data.length; i++) {
						var currenttime = new Date(data[i].created_date).getTime();
						var begintime = new Date(data[i - 1].created_date).getTime();

						if (currenttime - begintime > 1000 * 60) {
							data[i].flagtime = true;
						} else {
							data[i].flagtime = false;
						}
					}
					that.setData({
						newslist: data
					});

					that.bottom();
				}
      });

			that.getIntervalChat(that);
    }
  },

	getIntervalChat: function(that) {
		interval = setInterval(function () {
			wx.closeSocket();
			websocket.connect(that.data.chatInfo, function (res) {
				if (JSON.parse(res.data).data.length == 0) {
					that.setData({
						newslist: []
					});
				} else {
					var data = JSON.parse(res.data).data;
					data[0].flagtime = true;

					for (var i = 1; i < data.length; i++) {
						var currenttime = new Date(data[i].created_date).getTime();
						var begintime = new Date(data[i - 1].created_date).getTime();

						if (currenttime - begintime > 1000 * 60) {
							data[i].flagtime = true;
						} else {
							data[i].flagtime = false;
						}
					}
					that.setData({
						newslist: data
					});
				}
			});
		}, 5000);
	},

  // 页面卸载
  onUnload() {
		var that = this;
		clearInterval(interval);

		//将消息设置为已读
		wx.request({
			url: utils.basePath + '/article/v1/changeChatType',
			method: "post",
			data: {
				myphone: that.data.chatInfo.userInfo.account,
				app_sid: that.data.chatInfo.userInfo.app_sid,
				friendphone: that.data.chatInfo.friendInfo.account
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					wx.reLaunch({
						url: '/pages/friend/friend',
						success: function(res) {
							wx.closeSocket(function (res) {
								$Toast({
									content: '连接已断开!',
									type: 'error'
								});
							});
						},
						
					})
				} else {
					that.cancel();
					$Toast({
						content: res.data.err,
						type: 'error'
					});
				}
			}
		});
  },

  //事件处理函数
  send: function() {
    var that = this;

    if (that.data.message.trim() == "") {
      $Toast({
        content: '不能发送空消息!',
        type: 'error'
      });
    } else {
      setTimeout(function() {
        that.setData({
          increase: false
        });
      }, 500);

      //封装聊天记录参数
      var chatInfo = that.data.chatInfo;
      chatInfo.chat_content = that.data.message;
      chatInfo.chat_type = 0;
      chatInfo = JSON.stringify(chatInfo);

      websocket.send(chatInfo);
		
			//接受服务器消息
			wx.onSocketMessage(function(res) {
				var data = JSON.parse(res.data).data;
				data[0].flagtime = true;

				for (var i = 1; i < data.length; i++) {
					var currenttime = new Date(data[i].created_date).getTime();
					var begintime = new Date(data[i - 1].created_date).getTime();

					if (currenttime - begintime > 1000 * 60) {
						data[i].flagtime = true;
					} else {
						data[i].flagtime = false;
					}
				}
				that.setData({
					newslist: data
				});

				that.bottom();
			});
    }
  },

  //监听input值的改变
  bindChange(res) {
    this.setData({
      message: res.detail.value
    });
  },

  cleanInput() {
    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
    this.setData({
      message: this.data.message
    })
  },

  increase() {
    this.setData({
      increase: true,
      aniStyle: true
    })
  },

  //点击空白隐藏message下选框
  outbtn() {
    this.setData({
      increase: false,
      aniStyle: true
    })
  },

  //发送图片
  chooseImage() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
				console.log(tempFilePaths);

        wx.uploadFile({
					url: utils.basePath + '/users/upload_avatar', 
          filePath: tempFilePaths[0],
          name: 'avatar',
          headers: {
            'Content-Type': 'form-data'
          },

          success: function(res) {
						var result = JSON.parse(res.data);
            if (result.status == 200) {
              that.setData({
                increase: false
              });
							//上传图片操作
							var chatInfo = that.data.chatInfo;
							chatInfo.chat_content = result.payload.avatar_path;
							chatInfo.chat_type = 1;
							chatInfo = JSON.stringify(chatInfo);

							websocket.send(chatInfo);

							//接受服务器消息
							wx.onSocketMessage(function (res) {
								var data = JSON.parse(res.data).data;
								data[0].flagtime = true;

								for (var i = 1; i < data.length; i++) {
									var currenttime = new Date(data[i].created_date).getTime();
									var begintime = new Date(data[i - 1].created_date).getTime();

									if (currenttime - begintime > 1000 * 60) {
										data[i].flagtime = true;
									} else {
										data[i].flagtime = false;
									}
								}
								that.setData({
									newslist: data
								});

								that.bottom();
							});
            } else{
							$Toast({
								content: '图片上传失败!',
								type: 'error'
							});
						}
          }
        });
      }
    });
  },

  //图片预览
  previewImg(e) {
    var that = this
    //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到
    var res = e.target.dataset.src
    var list = this.data.previewImgList //页面的图片集合数组
    //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在
    if (list.indexOf(res) == -1) {
      this.data.previewImgList.push(res)
    }

    wx.previewImage({
      current: res, // 当前显示图片的http链接
      urls: that.data.previewImgList // 需要预览的图片http链接列表
    });
  },

  //聊天消息始终显示最底端
  bottom: function() {
    var query = wx.createSelectorQuery();
    query.select('#flag').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(function(res) {
			console.log(res);
      wx.pageScrollTo({
				scrollTop: res[1].scrollHeight // #the-id节点的下边界坐标
      });
      res[1].scrollTop; // 显示区域的竖直滚动位置
    })
  },
});